<!--用户页面-->
<!--动态的表格-->
<!-- Datatables -->
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet" />

<!-- page content -->
<div id="usersDiv" class="right_col" role="main">
	<div class="">
		<div class="page-title">
			<div class="title_left">
				<h3>Users <small>list</small></h3>
			</div>

			<div class="clearfix"></div>

			<!--row代表一行-->
			<div class="row">
				<div class="col-md-12 col-sm-12">
					<div class="x_panel">
						<div class="x_title">
							<!--button提交按钮，按钮名称为“新增”-->
							<button
									@click="initAddModel()"
									class="btn btn-primary"
									type="button"
									data-toggle="modal"
									data-target="#modelAdd">新增
							</button>
							<ul class="nav navbar-right panel_toolbox">
								<li>
									<a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
								</li>
								<li class="dropdown">
									<a
											href="#"
											class="dropdown-toggle"
											data-toggle="dropdown"
											role="button"
											aria-expanded="false"
									><i class="fa fa-wrench"></i
									></a>
									<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
										<a class="dropdown-item" href="#">Settings 1</a>
										<a class="dropdown-item" href="#">Settings 2</a>
									</div>
								</li>
								<li>
									<a class="close-link"><i class="fa fa-close"></i></a>
								</li>
							</ul>
							<div class="clearfix"></div>
						</div>
						<div class="x_content">
							<div class="row">
								<div class="col-sm-12">
									<div class="card-box table-responsive">
										<table
												id="datatable"
												class="table table-striped table-bordered"
												style="width: 100%"
										>
											<thead>
											<tr>
												<!--列名，数据来源于src\main\java\com\sfac\javaSpringBoot\modules\account\entity\User.java-->
												<th>ID</th>
												<th>User Name</th>
												<th>Email</th>
												<th>User Image</th>
												<th>Create Date</th>
												<th>Operation</th>   <!--对数据进行编辑，删除操作-->
											</tr>
											</thead>

											<tbody></tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- 引入 新增用户、编辑用户 模态框-->
	<div th:replace="account/userAdd"></div><!--增加user用户的功能由于users.html中功能实现太复杂，所以将其放到了userAdd.html中-->
	<div th:replace="account/userEdit"></div>
</div>

<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<script>
	//初始化一个对象usersVue
	var usersVue = new Vue({
		el: "#usersDiv",
		data: {
			user: {
				id: "",
				userName: "",
				email: "",
				password: "",
				userImage: "",
				createDate: "",
			},
			// 表格数据结构
			tableData: {
				recordsTotal: 0,
				recordsFiltered: 0,
				data: [],
			},
			usersTable: "",// 表格对象

			defaultPageSize: 5,// 默认页长为5
		},
		methods: {
			// 行数据结构
			rowData: function (id, userName, email, password, userImage, createDate) {
				var row = {};
				row.id = id;
				row.userName = userName;
				row.email = email;
				row.password = password;
				row.userImage = userImage;
				row.createDate = createDate;
				row.operate = function () {//operate为操作列，有“编辑”按钮，“删除”按钮
					return (
							"<a href='#' class='btn_editcolor' data-toggle='modal' data-target='#modelEdit' " +
							"onclick='initEditModal(\"" +
							id +
							"\")'>编辑</a>&nbsp;" +
							"<a href='javascript:void(0);' onclick='deleteModel(\"" +
							id +
							"\")' class='btn_editcolor'>删除</a>"
					);//两个按钮,一个“编辑”按钮，一个“删除”按钮
					//编辑按钮函数initEditModal函数在第260行代码
					//删除按钮函数deleteModel函数在第310行代码
				};
				return row;
			},
			// 初始化表格
			initTable: function () {
				var self = this;//this代表的是Vue
				$("#datatable").DataTable({
					paging: true, //是否分页
					serverSide: true, //开启后端分页
					pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
					pageLength: self.defaultPageSize, //定义初始的页长
					processing: true,//processing过程
					destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
					lengthChange: true, //控制是否能够调整每页的条数
					searching: true,//searching代表搜索框
					"data-show-refresh": true,//data展示时进行刷新
					ordering: true,//ordering代表排序
					autoWidth: false,//自动的改变每一列的宽度

					//触发了页面的数据之后，会进入ajax进行刷新
					ajax: function (data, callback, settings) {
						// 从data获取查询数据
						var columIndex = data.order[0].column;
						var direction = data.order[0].dir;
						var orderBy = data.columns[columIndex].name;
						var pageSize = data.length == undefined ? self.defaultPageSize : data.length;
						//拿到值之后，封装成search对象
						var search = {};
						search.currentPage = data.start / pageSize + 1;
						search.pageSize = pageSize;
						search.orderBy = orderBy;
						search.direction = direction;
						search.keyword = data.search.value;

						$.ajax({
							url: "/api/users",
							type: "post",
							contentType: "application/json",
							data: JSON.stringify(search),
							success: function (rs) {
								if (!rs) {
									layer.alert("请求出错，请稍后重试" + rs.errmsg, { icon: 2 });
									callback(self.tableData);
									return;
								}
								if (rs.list == null) {
									$("#moduleTable tbody tr").remove();
									$("#loading").remove();
									callback(self.tableData);
									return;
								}
								$("#loading").remove();
								var rowsData = [];
								for (var i = 0; i < rs.list.length; i++) {
									//包装行数据
									var row = self.rowData(
											rs.list[i].id,
											rs.list[i].userName,
											rs.list[i].email,
											rs.list[i].password,
											rs.list[i].userImage,
											rs.list[i].createDate
									);
									// 将行数据放到数组里
									rowsData.push(row);
								}
								//将获取到的数据拿给表格
								self.tableData.data = rowsData;
								self.tableData.recordsTotal = rs.total;
								self.tableData.recordsFiltered = rs.total;
								callback(self.tableData);//将表格数据交给callback函数进行回写
							},
							error: function (data) {
								layer.alert(data.responseText, { icon: 0 });
							},
						});
					},
					//将列名与后台数据库的列名进行一一对应
					columns: [
						//定义行数据字段
						{ data: "id", name: "id", sortable: true },
						{ data: "userName", name: "user_name", sortable: true },
						{ data: "email", name: "email", sortable: true },
						{ data: "userImage", name: "user_image", sortable: true },
						{ data: "createDate", name: "create_date", sortable: true },
						{ data: "operate", width: "80px", sortable: false },
					],
				});
			},
			// 初始化新增模型(初始化AddModel)
			//（再一次点击新增时，上一个新增的用户数据会自动置为空）
			initAddModel: function () {
				this.user = {
					id: "",
					userName: "",
					email: "",
					password: "",
					userImage: "",
					createDate: "",
				};
			},
			// 新增用户
			addUser: function () {
				if (this.user.userName == "" || this.user.email == "" || this.user.password == "") {
					layer.alert("用户名、邮箱、密码不能为空。", { icon: 0 });
					return;
				}
				console.log(this.user);

				var self = this;
				$.ajax({
					url: "/api/user",
					type: "post",
					contentType: "application/json",
					data: JSON.stringify(self.user),
					success: function (data) {
						if (data.status == 200) {
							$("#modelAdd").modal("hide");//关闭（隐藏）模态框
							self.initTable();//调用initTable
						} else {
							layer.msg(data.message, { icon: 0 });
						}
					},
					error: function (data) {
						layer.msg(data.responseText, { icon: 0 });
					},
				});
			},
			// 初始化编辑框
			initEditModal: function (id) {
				var self = this;
				$.ajax({
					url: "/api/user/" + id,
					type: "get",
					// contentType: "application/json",
					// data: JSON.stringify(self.user),
					success: function (data) {
						self.user = data;
					},
					error: function (data) {
						layer.msg(data.responseText, { icon: 0 });
					},
				});
			},
			updateModel: function () {
				if (this.user.userName == "" || this.user.email == "") {
					layer.alert("用户名、邮箱、密码不能为空。", { icon: 0 });
					return;
				}
				console.log(this.user);

				var self = this;
				$.ajax({
					url: "/api/user/",
					type: "put",
					contentType: "application/json",
					data: JSON.stringify(self.user),
					success: function (data) {
						if (data.status == 200) {
							$("#modelEdit").modal("hide");
							self.initTable();
						} else {
							layer.msg(data.message, { icon: 0 });
						}
					},
					error: function (data) {
						layer.msg(data.responseText, { icon: 0 });
					},
				});
			},
			//初始化删除框
			deleteModel: function (id) {
				var self = this;     //this对象赋值给self
				bootbox.confirm("是否确认删除？", function (result) {
					if (result) {
						$.ajax({
							url: "/api/user/" + id,
							type: "delete",
							success: function (rs) {
								if (rs.status == 200) {
									self.initTable();
								} else {
									layer.alert(rs.message, { icon: 0 });
								}
							},
							error: function (data) {
								layer.alert(data.responseText, { icon: 0 });
							},
						});
					}
				});
			},
		},
		created: function () {
			window.initEditModal = this.initEditModal;
			//必须要把initEditModal拿给window，才能够用onclick调用
			window.deleteModel = this.deleteModel;
			//同上
		},
		mounted: function () {
			this.initTable();
		},
	});
</script>

<!--.pagination {
    float: right;
}
.dataTables_paginate li.active a {
	background-color: #1ABB9C !important;
}//custom.css中插入此段代码，将表格右下方的那个换页按钮进行右对齐
-->